//
//  OTRBaseApi.m
//  QWNetwork
//
//  Created by ZhangYanhua on 15/12/16.
//  Copyright © 2015年 zhangyh. All rights reserved.
//

#import "OTRBaseApi.h"
#import "OTRRequestError.h"
#import <YYModel/YYModel.h>

@implementation OTRBaseApi

- (Class)expectedJsonObjClass
{
    return [NSDictionary class];
}

- (Class)expectedModelCalss
{
    return [self expectedJsonObjClass];
}

- (id)getCachedModel
{
    id cachedData = [self getCachedJson];
    
    [self handleResultWithResonseData:cachedData error:nil];
    
    return self.resultModel;
}

- (BOOL)handleResultWithResonseData:(id)responseData error:(NSError *)error
{
    BOOL isSuccess = NO;

    NSNumber *errCode = nil;
    NSString *errMsg = nil;
    if (responseData != nil) {
        NSDictionary *dict = nil;
        dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:NULL];

        errCode = [dict valueForKey:@"ok"];
        errMsg = [dict valueForKey:@"msg"];

        if (errCode != nil && [errCode integerValue] == TROAD_ERROR_OK) {
            id objDict = [dict objectForKey:@"obj"];
            if (!objDict || [objDict isKindOfClass:[self expectedJsonObjClass]]) {
                self.resultModel = [[self expectedModelCalss] yy_modelWithDictionary:objDict];

                isSuccess = YES;
            }
            else {
                errCode =@(TROAD_ERROR_INVALID_DATA_FORMAT);
                errMsg = TROAD_MSG_INVALID_DATA_FORMAT;
            }
        } else {
            errCode =@(TROAD_ERROR_ASIHTTP);
            errMsg = TROAD_MSG_ASIHTTP;
        }
    }

    [self p_buildErrorInfoWithRequestError:error
                         responseErrorCode:errCode
                          responseErrorMsg:errMsg];

    return isSuccess;
}

#pragma mark -
#pragma mark private methods

- (void)p_buildErrorInfoWithRequestError:(NSError *)error
                       responseErrorCode:(NSNumber *)errCode
                        responseErrorMsg:(NSString *)errMsg
{
    if (error) {
        // ASIHttpRequest发送请求时发生错误，现在都统一默认为网络不可用。
        self.lastError = [NSError errorWithDomain:kTRoadErrorDomain
                                             code:TROAD_ERROR_ASIHTTP
                                         userInfo:@{NSLocalizedFailureReasonErrorKey:TROAD_MSG_ASIHTTP}];
        
    } else if (nil == errCode || [errCode intValue] != TROAD_ERROR_OK) {
        errMsg = [errMsg length] ? errMsg : NSLocalizedString(@"Unknown error", nil);
        
        self.lastError = [NSError errorWithDomain:kTRoadErrorDomain
                                             code:[errCode integerValue]
                                         userInfo:@{NSLocalizedFailureReasonErrorKey:errMsg}];
    } else {
        self.lastError = nil;
    }
}

@end
